import Cookies from 'js-cookie'

const tokenExpires = function () {
    return new Date(new Date().getTime() + 24 * 60 * 60 * 1000)
}
//token管理
export const authToken = {
    tokenKey: "token",

    hasToken: function () {
        return Cookies.get(this.tokenKey)
    },

    setToken: function (token) {
        Cookies.set(this.tokenKey, token, {
            expires: tokenExpires()
        })
    },

    removeToken: function () {
        Cookies.remove(this.tokenKey)
    },
}

//菜单处理
export const menusFormat = function (data, parentKey = null) {
    let menus = [], acl = [];
    if (data) {
        data.forEach(v => {
            if(v.level === 1) {
                //菜单
                let menu = {
                    ...v,
                    parentId: parentKey,
                    title: v.title,
                    icon: v.icon,
                    path: v.path || '/home'
                }
            
                if (v.children && v.children.length) {
                    const data = menusFormat(v.children, v.id)
                    menu.children = data.menus
                    acl = [...acl, ...data.acl]
                }
                menus.push(menu)
            }
            if(v.level === 3) {
                //按钮
                acl.push(v.permission);
                if (v.children && v.children.length) {
                    const data = menusFormat(v.children, v.id)
                    acl = [...acl, ...data.acl]
                }
            }
        })
    }
    return { menus, acl }
}
